package a07_二叉树;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * a03_层序遍历01_二叉树的层序遍历
 * </p>
 *
 * @author flyduck
 * @since 2024-08-20
 */
public class a05_层序遍历01_二叉树的层序遍历复习0 {

    public static void main(String[] args) {
        Deque<Integer> deque = new LinkedList<>();
        deque.push(1);
        deque.push(2);
        deque.push(3);
        System.out.println(deque.pollLast());//1
        TreeNode root = new TreeNode(
                6,
                new TreeNode(4,new TreeNode(1),new TreeNode(3)),
                new TreeNode(7,new TreeNode(5),new TreeNode(8)));
//        TreeNode root = new TreeNode(
//                6,
//                new TreeNode(4),
//                new TreeNode(7,new TreeNode(5),new TreeNode(8)));
        List<List<Integer>> lists = levelOrder(root);
        System.out.println(lists);
    }


    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> resultList = new ArrayList<>();
        if (root == null) {
            return resultList;
        }

        Deque<TreeNode> deque = new LinkedList<>();
        deque.push(root);

        while (!deque.isEmpty()) {
            int popSize = deque.size();
            List<Integer> result = new ArrayList<>();
            while (popSize > 0){
                TreeNode popNode = deque.pollLast();
                result.add(popNode.val);

                if (popNode.left != null) {
                    deque.push(popNode.left);
                }

                if (popNode.right != null) {
                    deque.push(popNode.right);
                }
                popSize--;
            }
            resultList.add(result);
        }
        return resultList;

    }
}
